<template>
  <t-dialog v-model:visible="formVisible" :header="formData.id ? '修改用户' : '新增用户'" :width="680" :footer="false"
    :on-closed="closed">
    <template #body>
      <!-- 表单内容 -->
      <t-form ref="form" :data="formData" :rules="rules" :reset-type="resetType" :label-width="100" @submit="onSubmit">
        <t-form-item label="用户名" name="username">
          <t-input v-model="formData.username" :style="{ width: '480px' }" placeholder="请输入用户名" />
        </t-form-item>
        <t-form-item label="所属角色" name="admin_role_id">
          <t-select v-model="formData.admin_role_id" class="demo-select-base" clearable filterable
            :style="{ width: '480px' }">
            <t-option v-for="(item, index) in options" :key="index" :value="item.value" :label="item.label">
              {{ item.label }}
            </t-option>
          </t-select>
        </t-form-item>
        <template v-if="formData.id == 0">
          <t-form-item label="密码" name="password" :rules="[{ required: true, message: '密码不能为空', type: 'error' }]">
            <t-input v-model="formData.password" type="password" :style="{ width: '480px' }" placeholder="请输入密码" />
          </t-form-item>
        </template>
        <template v-else>
          <t-form-item label="密码" name="password">
            <t-input v-model="formData.password" type="password" :style="{ width: '480px' }" placeholder="请输入密码" />
          </t-form-item>
        </template>
        <t-form-item label="失效日期" name="expiration_date">
          <t-date-picker v-model="formData.expiration_date" :style="{ width: '480px' }" mode="date" clearable />
        </t-form-item>
        <t-form-item style="float: right">
          <t-button variant="outline" @click="onClickCloseBtn">取消</t-button>
          <t-button theme="primary" type="submit">确定</t-button>
        </t-form-item>
      </t-form>
    </template>
  </t-dialog>
  <t-loading :loading="loading" text="加载中..." fullscreen />
</template>

<script setup lang="ts">
import { FormRules, MessagePlugin, SubmitContext } from 'tdesign-vue-next';
import type { PropType } from 'vue';
import { onMounted, ref, watch } from 'vue';

import { saveUser } from '@/api/admin/user';
import { getRole } from '@/api/admin/role';

const form = ref(null);

// 父给子传值
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  data: Object as PropType<FormData>,
});

// 加载
const loading = ref(false);

export interface FormData {
  id: number;
  username: string;
  admin_role_id: number;
  password: string;
  expiration_date: string;
}
// 初始化数据
const INITIAL_DATA: FormData = {
  id: 0,
  admin_role_id: null,
  username: '',
  password: '',
  expiration_date: '',
};
const formVisible = ref(false);
const formData = ref({ ...INITIAL_DATA });
const resetType = 'initial';

// 表单规则
const rules: FormRules<FormData> = {
  username: [{ required: true, message: '用户名不能为空', type: 'error' }],
  admin_role_id: [{ required: true, message: '角色不能为空', type: 'error' }],
  expiration_date: [{ required: true, message: '失效日期不能为空', type: 'error' }],
};

onMounted(() => {
  queryRole();
});

// 取消按钮
const onClickCloseBtn = () => {
  formVisible.value = false;
};
// 关闭dialog是reset from
const closed = () => {
  form.value.reset();
  formData.value.id = 0;
};

// 提交按钮
const onSubmit = async ({ firstError }: SubmitContext<FormData>) => {
  if (!firstError) {
    try {
      loading.value = true;
      await saveUser(formData.value);
      emit("refreshData");
    } catch (e) {
      if (e.response && e.response.data.code === 995) {
        MessagePlugin.error(e.response.data.message);
      } else {
        MessagePlugin.error('系统错误');
      }
    } finally {
      loading.value = false;
      formVisible.value = false;
    }
  } else {
    // console.log('Errors: ', validateResult);
    MessagePlugin.warning(firstError);
  }
};

const options = ref([]);
const queryRole = async () => {
  try {
    const { list } = await getRole();
    list.forEach((element, index) => {
      options.value.push({ label: element.name, value: element.id });
    });
  } catch (e) {
    if (e.response && e.response.data.code === 995) {
      MessagePlugin.error(e.response.data.message);
    } else {
      MessagePlugin.error('系统错误');
    }
  }
}

// 监视
const emit = defineEmits(['update:visible', 'refreshData']);
watch(
  () => formVisible.value,
  (val) => {
    emit('update:visible', val);
  },
);
watch(
  () => props.visible,
  (val) => {
    formVisible.value = val;
  },
);
watch(
  () => props.data,
  (val) => {
    formData.value = val;
  },
);
</script>
